package cn.iocoder.boot.service.impl;

import cn.hutool.json.JSONObject;
import cn.iocoder.boot.dto.ConfigQueryTO;
import cn.iocoder.boot.dto.ImportConfigTO;
import cn.iocoder.boot.dto.ImportStockTO;
import cn.iocoder.boot.dto.SearchModelTO;
import cn.iocoder.boot.entity.ComponentSupplier;
import cn.iocoder.boot.entity.SalePriceConfig;
import cn.iocoder.boot.mapper.SalePriceConfigMapper;
import cn.iocoder.boot.service.ComponentStockService;
import cn.iocoder.boot.service.SalePriceConfigService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.jsoup.internal.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.extension.toolkit.Db.updateById;

@Service
public class SalePriceConfigServiceImpl implements SalePriceConfigService {

    @Resource
    private SalePriceConfigMapper baseMapper;

    @Override
    public Page<SalePriceConfig> list(ConfigQueryTO to) {



        Page<SalePriceConfig> page = new Page<>(to.getPageNo(), to.getPageSize());


        LambdaQueryWrapper<SalePriceConfig> queryWrapper = new LambdaQueryWrapper<>();

        // 根据不同的条件，拼接查询
        if (!StringUtil.isBlank(to.getCurrency())) {
            queryWrapper.eq(SalePriceConfig::getCurrency, to.getCurrency());
        }
        if (to.getType() != null) {
            queryWrapper.eq(SalePriceConfig::getType, to.getType());
        }
        if (!StringUtil.isBlank(to.getModel())) {
            queryWrapper.eq(SalePriceConfig::getModel, to.getModel());
        }
        //
        queryWrapper.eq(SalePriceConfig::getType, 1);

        Page<SalePriceConfig> parentList = baseMapper.selectPage(page, queryWrapper);

        return parentList;


    }

    @Override
    public Boolean updateSalePriceConfig(SalePriceConfig salePriceConfig) {
        return updateById(salePriceConfig);
    }

    @Override
    public Boolean insertSalePriceConfig(SalePriceConfig salePriceConfig) {
        salePriceConfig.setType(1);
        return baseMapper.insert(salePriceConfig) > 0;
    }

    @Override
    public Boolean deleteSalePriceConfig(Long id) {
        baseMapper.deleteById(id);
        return true;
    }

    @Override
    public SalePriceConfig getSalePriceConfig(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public Boolean importSalePriceConfig(MultipartFile file) throws IOException {
        List<ImportConfigTO> sheetData = new ArrayList<>();

        try (InputStream inputStream = file.getInputStream()) {

            EasyExcel.read(inputStream, ImportConfigTO.class, new PageReadListener<ImportConfigTO>(dataList -> {
                sheetData.addAll(dataList);
            })).sheet(0).doRead();
        }

        List<SalePriceConfig> collect = sheetData.stream()
                .map(importConfig -> {
                    SalePriceConfig salePriceConfig = new SalePriceConfig();
                    salePriceConfig.setModel(importConfig.getModel());
                    salePriceConfig.setCurrency(importConfig.getCurrency());
//                    salePriceConfig.setNum(importConfig.getNum());
                    salePriceConfig.setValue(new BigDecimal(importConfig.getValue())); // Assuming value is a valid numeric string
                    return salePriceConfig;
                })
                .collect(Collectors.toList());

        baseMapper.insert(collect);


        return true;
    }

    @Override
    public SalePriceConfig searchModel(SearchModelTO salePriceConfig) {

        if(!StringUtil.isBlank(salePriceConfig.getModel())&&!StringUtil.isBlank(salePriceConfig.getCurrency())){
            LambdaQueryWrapper<SalePriceConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SalePriceConfig::getModel, salePriceConfig.getModel())
                    .eq(SalePriceConfig::getCurrency, salePriceConfig.getCurrency());
            SalePriceConfig config = baseMapper.selectOne(queryWrapper);
            if(config==null){
                queryWrapper.clear();
                queryWrapper.eq(SalePriceConfig::getType, 2);
                return baseMapper.selectOne(queryWrapper);
            }else{
                return baseMapper.selectOne(queryWrapper);
            }


        }else{

            LambdaQueryWrapper<SalePriceConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SalePriceConfig::getType, 2);
            return baseMapper.selectOne(queryWrapper);

        }




    }


    public String getSaleJson(String json,String model,String  currency){

        LambdaQueryWrapper<SalePriceConfig> queryWrapper = new LambdaQueryWrapper<>();

        // 根据不同的条件，拼接查询
        if (!StringUtil.isBlank(currency)) {
            queryWrapper.eq(SalePriceConfig::getCurrency,currency);
        }

        if (!StringUtil.isBlank(model)) {
            queryWrapper.eq(SalePriceConfig::getModel, model);
        }

       SalePriceConfig salePriceConfigs = baseMapper.selectOne(queryWrapper);

        //找到了单独的配置
        if(salePriceConfigs!=null){

            //生成销售价json
            JSONArray resultArray = new JSONArray();

            // 遍历rmb和nums数组

                JSONObject priceInfo = new JSONObject();

                String unitPrice = String.valueOf(salePriceConfigs.getValue());
// Parse to double and format to 4 decimal places
                double price = Double.parseDouble(unitPrice);
                String formattedPrice = String.format("%.4f", price);

                priceInfo.put("Price", formattedPrice);

                priceInfo.put("Currency", currency);
                priceInfo.put("Quantity", 1);

                // 将 priceInfo 添加到结果数组中
                resultArray.add(priceInfo);

            return resultArray.toJSONString();

        }
        else{
            //没找到，需要公共的配置

            queryWrapper.clear();
            queryWrapper.eq(SalePriceConfig::getType, 2);
            SalePriceConfig salePriceConfig = baseMapper.selectOne(queryWrapper);
            BigDecimal value = salePriceConfig.getValue();




            JSONArray jsonArray = JSON.parseArray(json);
            for (int k = 0; k < jsonArray.size(); k++) {
                com.alibaba.fastjson.JSONObject tem = (com.alibaba.fastjson.JSONObject) jsonArray.get(k);

                BigDecimal price = new BigDecimal(tem.getString("Price"));
                BigDecimal result = price.multiply(value);

                result = result.setScale(4, RoundingMode.HALF_UP);

                tem.put("Price", result); // 直接更新原 jsonArray 中的元素

            }



            return jsonArray.toJSONString();

        }





    }

}
